import os.path

from django.shortcuts import render
from django.http import HttpResponse
from app.report.xlsx import writer
from app.report.xlsx import read
from rest_framework.views import APIView
from packages.response import response
from core.settings import EXCEL_ROOT, UPLOAD_EXCEL_URL


class TestWriteView(APIView):
    def post(self, request):
        data = request.data
        writer_class = writer.TestWriter
        writer_obj = writer_class().run(filename=data.get('filename'))
        return response(data=writer_obj)


class TestReadView(APIView):
    def save_file(self, data):
        obj = data.get('file')
        file_name = obj.name
        dir_path = os.path.join(EXCEL_ROOT, UPLOAD_EXCEL_URL)

        if not os.path.exists(dir_path):
            os.makedirs(dir_path)

        absolute_path = os.path.join(dir_path, file_name)
        relative_path = f'./{os.path.join(EXCEL_ROOT, UPLOAD_EXCEL_URL, file_name)}'

        with open(absolute_path, 'wb') as fw:
            for chunk in obj.chunks():
                fw.write(chunk)

        return absolute_path, relative_path

    def post(self, request):
        # from 表单
        # 存储上传文件，返回路径
        absolute_path, relative_path = self.save_file(data = request.data)
        # 根据返回路径，保存文件数据
        read_class = read.TestWriter
        read_obj = read_class(absolute_path).run()
        return response(data=read_obj)